package com.hzx.zhihu.controller;

import com.hzx.zhihu.domain.po.Resp;
import com.hzx.zhihu.domain.po.Result;
import com.hzx.zhihu.exception.AppException;
import com.hzx.zhihu.exception.AppExceptionCodeMsg;
import com.hzx.zhihu.utils.AliOssUtil;
import com.hzx.zhihu.utils.ImageSimilarityUtil;
import com.hzx.zhihu.utils.TencentUtil;
import com.tencentcloudapi.ai3d.v20250513.models.QueryHunyuanTo3DJobRequest;
import com.tencentcloudapi.ai3d.v20250513.models.QueryHunyuanTo3DJobResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/test")
public class TestController {
    @Autowired
    private TencentUtil tencentUtil;

    @Autowired
    private RedisTemplate redisTemplate;
    @PostMapping("/3d")
    public Resp<QueryHunyuanTo3DJobResponse> tencent(MultipartFile file) throws Exception {
        if (file == null) {
            throw new AppException(500, "文件为空");
        }

        // 1. 计算当前图片的哈希值
        String currentHash = ImageSimilarityUtil.calculateAverageHash(file.getInputStream());

        // 2. 从Redis中获取所有已缓存的图片哈希值（实际中可优化存储结构，如用集合存储所有哈希）
        Set<String> cachedHashKeys = redisTemplate.keys("3d_model:*");
        if (cachedHashKeys != null) {
            for (String key : cachedHashKeys) {
                String cachedHash = key.replace("3d_model:", "");
                // 3. 比较哈希值，若相似则返回缓存结果
                if (ImageSimilarityUtil.isSimilar(currentHash, cachedHash, 5)) {
                    QueryHunyuanTo3DJobResponse cachedResult =
                            (QueryHunyuanTo3DJobResponse) redisTemplate.opsForValue().get(key);
                    return Resp.success(cachedResult);
                }
            }
        }

        // 4. 无相似缓存，调用API并缓存结果（包含当前图片的哈希值）
        String image = AliOssUtil.uploadFile(file.getOriginalFilename(), file.getInputStream());
        QueryHunyuanTo3DJobResponse result = tencentUtil.createQueryHunyuanTo3DJobRequest(image);
        redisTemplate.opsForValue().set("3d_model:" + currentHash, result, 7, TimeUnit.DAYS);

        return Resp.success(result);
    }

    //图片上传
    @PostMapping("/upload")
    public Resp upload(MultipartFile  file){
        try {
            String url = AliOssUtil.uploadFile(file.getOriginalFilename(), file.getInputStream());
            return Resp.success(url);
        } catch (Exception e) {
            e.printStackTrace();
            return Resp.error(500,"上传失败");
        }
    }
}


